package com.ctshk.rpc.certificate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.certificate.dto.AppointmentInfoDTO;
import com.ctshk.rpc.certificate.dto.CertificateAcceptDTO;
import com.ctshk.rpc.certificate.dto.CertificateHkMacauDTO;
import com.ctshk.rpc.certificate.entity.CertificateHkMacau;
import com.ctshk.rpc.certificate.mapper.CertificateBusinessMapper;
import com.ctshk.rpc.certificate.mapper.CertificateHkMacauMapper;
import com.ctshk.rpc.certificate.req.CertificateAcceptPageReq;
import com.ctshk.rpc.certificate.req.CertificateHkMacauReq;
import com.ctshk.rpc.certificate.req.ProcCommonCertificateReq;
import com.ctshk.rpc.certificate.req.QueryAppointmentInfoReq;
import com.ctshk.rpc.certificate.service.ICertificateHkMacauService;
import com.ctshk.rpc.certificate.utils.OrderUtil;
import com.ctshk.rpc.system.service.IValidateService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 港澳通行证 服务实现类
 * </p>
 *
 * @author 谢诗宏
 * @since 2021-03-25
 */
@DubboService
public class CertificateHkMacauServiceImpl extends ServiceImpl<CertificateHkMacauMapper, CertificateHkMacau> implements ICertificateHkMacauService {

    @Autowired
    private CertificateHkMacauMapper hkMacauMapper;

    @Autowired
    private CertificateBusinessMapper businessMapper;

    @DubboReference
    private IValidateService validateService;
    
    @Override
    public Result saveHkMacau(CertificateHkMacauReq certificateHkMacauReq, Long userId) {
        if (userId == null) {
            return Result.failed(SystemError.USER_1000);
        }
        if (certificateHkMacauReq == null) {
            return Result.failed(SystemError.SYS_416);
        }
        
        // 有id保存
        CertificateHkMacau certificateHkMacau;
        if (null != certificateHkMacauReq.getId()) {
            certificateHkMacau = hkMacauMapper.selectById(certificateHkMacauReq.getId());
            if (Objects.isNull(certificateHkMacau)) {
                return Result.failed(SystemError.SYS_411);
            }
            BeanUtils.copyProperties(certificateHkMacauReq, certificateHkMacau);
            certificateHkMacau.setModifiedId(userId);
            certificateHkMacau.setGmtModified(LocalDateTime.now());
            hkMacauMapper.updateById(certificateHkMacau);
        } else {
            // 保存预约单据
            certificateHkMacau = new CertificateHkMacau();
            BeanUtils.copyProperties(certificateHkMacauReq, certificateHkMacau);
            Long permitId = SnowflakeIdWorker.nextId();
            certificateHkMacau.setId(permitId);
            String registerNumber = OrderUtil.getReentryPermitRegisterNumber();
            certificateHkMacau.setRegisterNumber(registerNumber);
            certificateHkMacau.setCreateId(userId);
            certificateHkMacau.setGmtCreate(LocalDateTime.now());
            certificateHkMacau.setAcceptStatus(1);
            certificateHkMacau.setIsDeleted(0);
            hkMacauMapper.insert(certificateHkMacau);
        }

        // 预约办证中心
        if (certificateHkMacau.getSubmissionStatus() == 1) {
            Long res = businessMapper.reserveReentryPermit(certificateHkMacauReq.getName(), certificateHkMacauReq.getBusinessHallId(),
                    certificateHkMacauReq.getReserveDate(), certificateHkMacauReq.getReserveTime());
            if (res != 1) {
                return Result.failed(new BusinessException(SystemError.CERTIFICATE_BUSINESS_16002));
            }
        }
        return Result.success(certificateHkMacau.getId());
    }

    @Override
    public CertificateHkMacauDTO queryDetail(Long id) {
        CertificateHkMacau certificateHkMacau = hkMacauMapper.selectById(id);
        if (Objects.isNull(certificateHkMacau)) {
            throw new BusinessException(SystemError.SYS_411);
        }
        CertificateHkMacauDTO hkMacauDTO = new CertificateHkMacauDTO();
        BeanUtils.copyProperties(certificateHkMacau, hkMacauDTO);
        return hkMacauDTO;
    }

    @Override
    public Result updateHkMacau(CertificateHkMacauReq certificateHkMacauReq, Long userId) {
        if (userId == null) {
            return Result.failed(SystemError.USER_1000);
        }
        if (certificateHkMacauReq == null) {
            return Result.failed(SystemError.SYS_416);
        }
        CertificateHkMacau certificateHkMacau = hkMacauMapper.selectById(certificateHkMacauReq.getId());
        if (Objects.isNull(certificateHkMacau)) {
            return Result.failed(SystemError.SYS_411);
        }
        BeanUtils.copyProperties(certificateHkMacauReq, certificateHkMacau);
        certificateHkMacau.setModifiedId(userId);
        certificateHkMacau.setGmtModified(LocalDateTime.now());
        hkMacauMapper.updateById(certificateHkMacau);
        return Result.success();
    }

    @Override
    public Result procReserveHkMacau(ProcCommonCertificateReq procReserveHkMacauReq, Long userId) {
        if (userId == null) {
            return Result.failed(SystemError.USER_1000);
        }
        if (procReserveHkMacauReq == null) {
            return Result.failed(SystemError.SYS_416);
        }
        CertificateHkMacau certificateHkMacau = hkMacauMapper.selectById(procReserveHkMacauReq.getId());
        if (Objects.isNull(certificateHkMacau)) {
            return Result.failed(SystemError.SYS_411);
        }
        certificateHkMacau.setAcceptStatus(procReserveHkMacauReq.getAcceptStatus());
        certificateHkMacau.setModifiedId(userId);
        certificateHkMacau.setGmtModified(LocalDateTime.now());
        certificateHkMacau.setAcceptDesc(procReserveHkMacauReq.getAcceptDesc());
        hkMacauMapper.updateById(certificateHkMacau);
        return Result.success();
    }

    @Override
    public PageResponse<CertificateAcceptDTO> queryCertificateAcceptList(CertificateAcceptPageReq req) {
        Page<CertificateHkMacau> certificatePage = new Page<>(req.getPageNo(), req.getPageSize());
        QueryWrapper<CertificateHkMacau> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(null != req.getApplyTypeId(), CertificateHkMacau::getApplyTypeId, req.getApplyTypeId());
        queryWrapper.lambda().like(StringUtils.isNotBlank(req.getPhoneNum()), CertificateHkMacau::getPhoneNum, req.getPhoneNum());
        queryWrapper.lambda().like(StringUtils.isNotBlank(req.getEmail()), CertificateHkMacau::getEmail, req.getEmail());
        queryWrapper.lambda().eq(null != req.getAcceptStatus(), CertificateHkMacau::getAcceptStatus, req.getAcceptStatus());

        // 处理时间区间不包括右边界问题
        if (null != req.getGmtCreateEnd()) {
            req.setGmtCreateEnd(req.getGmtCreateEnd().plusDays(1));
        }
        queryWrapper.lambda().between((null != req.getGmtCreateBegin() && null != req.getGmtCreateEnd()), CertificateHkMacau::getGmtCreate,req.getGmtCreateBegin(),req.getGmtCreateEnd());
        Page<CertificateHkMacau> iPage = hkMacauMapper.selectPage(certificatePage, queryWrapper);
        List<CertificateHkMacau> records = iPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return new PageResponse<>(new ArrayList<>(), iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
        }
        List<CertificateAcceptDTO> certificateAcceptQueryDTOList = EntityUtil.copyList(records, CertificateAcceptDTO.class);
        certificateAcceptQueryDTOList.forEach(record -> record.setCnName("-"));
        return new PageResponse<>(certificateAcceptQueryDTOList, iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
    }

    @Override
    public Result queryAppointmentInfo(QueryAppointmentInfoReq queryAppointmentInfoReq, Long userId) {
        if (userId == null) {
            return Result.failed(SystemError.USER_1000);
        }
        validateService.check(queryAppointmentInfoReq.getKey(), queryAppointmentInfoReq.getCode());
        CertificateHkMacau macauTravel = hkMacauMapper.selectOne(new QueryWrapper<CertificateHkMacau>().lambda()
                .eq(null != queryAppointmentInfoReq.getId(), CertificateHkMacau::getId, queryAppointmentInfoReq.getId())
                .eq(StringUtils.isNotBlank(queryAppointmentInfoReq.getCertificateNo()), CertificateHkMacau::getCertificateNo, queryAppointmentInfoReq.getCertificateNo())
                .eq(queryAppointmentInfoReq.getBirthday() != null, CertificateHkMacau::getBirthday, queryAppointmentInfoReq.getBirthday())
                .eq(StringUtils.isNotBlank(queryAppointmentInfoReq.getRegisterNumber()), CertificateHkMacau::getRegisterNumber, queryAppointmentInfoReq.getRegisterNumber()));
        AppointmentInfoDTO appointmentInfoDTO = new AppointmentInfoDTO();
        BeanUtils.copyProperties(macauTravel, appointmentInfoDTO);
        return Result.success(appointmentInfoDTO);
    }

    @Override
    public Result cancelAppointment(Long id, Long userId) {
        CertificateHkMacau macauTravel = hkMacauMapper.selectById(id);
        if (Objects.isNull(macauTravel)) {
            return Result.failed(SystemError.SYS_411);
        }
        macauTravel.setAcceptStatus(0);
        hkMacauMapper.updateById(macauTravel);
        return Result.success(macauTravel.getRegisterNumber());
    }
}
